package mt.comm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.net.Socket;
import java.net.UnknownHostException;

import mt.Order;

public class ClientCommImp implements ClientComm {

	public final static int DEFAULT_PORT = 5025;
	Socket socket     = null;
	ObjectInputStream  is = null;
	ObjectOutputStream     os = null;

	@Override
	public void connect(String host, String nickname)
								throws UnknownHostException, IOException {

		socket = new Socket(host, DEFAULT_PORT);
		os = new ObjectOutputStream(socket.getOutputStream());
		is = new ObjectInputStream(socket.getInputStream());
		os.writeObject(nickname);
	}

	@Override
	public boolean isConnected() {
		try {
			is.available();
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	@Override
	public void disconnect() {
		
		 try {
             if (os != null) os.close();
             if (is != null) is.close();
             if (socket != null ) socket.close();
           }
           catch (IOException e) { 
               // if an I/O error occurs when closing this socket
				e.printStackTrace();
           }
	}

	@Override
	public ClientSideMessage getNextMessage() {
		
			try {
				return (ClientSideMessage)is.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.disconnect();
			}
		return null;
	}

	@Override
	public boolean hasNextMessage() {
		try {
			return (is.available()>0)?true:false;
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void sendOrder(Order order) {
		// TODO Auto-generated method stub
		try {
			os.writeObject(order);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
